package com.edais.service.imp;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.edais.dao.ShopVouchersDao;
import com.edais.dao.SystemSettingDao;
import com.edais.domain.ShopVouchers;
import com.edais.service.ShopVouchersService;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import com.edais.util.DES3Util;
import com.edais.util.MacUtil;
import com.edais.util.StringUtil;
@Service

@Transactional
public class ShopVouchersServiceImpl implements ShopVouchersService {
	private static final Log logger = LogFactory.getLog(ShopVouchersServiceImpl.class);
	
	@Autowired
	private SystemSettingDao systemSettingDao;
	
	@Autowired
	private ShopVouchersDao shopVouchersDao;
	
	
	/**
	 * 获取兑换券
	 * @param paramsMap
	 * @return rtnMap
	 * @throws Exception
	 */
	@Override
	public Map<String, String> addShopVouchers(Map<String, Object> paramsMap)
			throws Exception {
		Map<String,String> rtnMap = new HashMap<String,String>();
		String yygkg = systemSettingDao.getSystemSettingValueByName("yygkg");
		if("0".equals(yygkg)) {
			rtnMap.put("rescode", Consts.SUCCESS_CODE);
			rtnMap.put("resmsg", "");
			rtnMap.put("resmsg_cn", "一元购开关关闭状态！");
			return rtnMap;
		}
		// 用户id
		String userId = paramsMap.get("userId") == null ? "" : paramsMap.get("userId").toString();
		// 用户手机号
		String mobile = paramsMap.get("mobile") == null ? "" : paramsMap.get("mobile").toString();
		// 兑换券id
		String voucherId = paramsMap.get("voucherId") == null ? "" : paramsMap.get("voucherId").toString();
		// 来源
		String source = paramsMap.get("source") == null ? "" : paramsMap.get("source").toString();
		// 订单id
		String orderId = paramsMap.get("orderId") == null ? "" : paramsMap.get("orderId").toString();
		// 赠送人
		String giftStaff = paramsMap.get("giftStaff") == null ? "" : paramsMap.get("giftStaff").toString();
		
		logger.info("userId:" + userId + "mobile:" + mobile + "voucherId:" + voucherId 
					+ "source:" + source + "orderId:" + orderId + "giftStaff:" + giftStaff);
		
		if (StringUtil.isEmpty(userId) || StringUtil.isEmpty(mobile) 
				|| StringUtil.isEmpty(voucherId) || StringUtil.isEmpty(source)) {
			rtnMap.put("rescode", Consts.CHECK_CODE);
			rtnMap.put("resmsg", "");
			rtnMap.put("resmsg_cn", "该兑换券类型不存在！");
			return rtnMap;
		}
		
		Map<String,String> selSysVoucher = shopVouchersDao.selSysVoucher(paramsMap);
		if (null != selSysVoucher) {
			
			String validity = selSysVoucher.get("validity")==null?"":selSysVoucher.get("validity");
			String voucherType = selSysVoucher.get("voucherTypeId");
			String voucherAmount = selSysVoucher.get("voucherAmount");

			Calendar cal = Calendar.getInstance();
			Date nowDate = cal.getTime();
			if (!"".equals(validity)) {
				cal.add(Calendar.DATE, Integer.parseInt(validity));
			} else {
				cal.add(Calendar.DATE, 29);
			}
			Date endTime = cal.getTime();
			ShopVouchers shopVour = new ShopVouchers(Long.parseLong(userId),mobile,
					Integer.parseInt(voucherId),voucherType,nowDate,endTime,
					orderId,new BigDecimal(voucherAmount),source,giftStaff);
			shopVouchersDao.addShopVoucher(shopVour);
		} else {
			rtnMap.put("rescode", Consts.CHECK_CODE);
			rtnMap.put("resmsg", "");
			rtnMap.put("resmsg_cn", "该兑换券类型不存在！");
			return rtnMap;
		}
		rtnMap.put("rescode", Consts.SUCCESS_CODE);
		rtnMap.put("resmsg", "");
		rtnMap.put("resmsg_cn", "获取兑换券成功！");
		return rtnMap;
	}
	
	/**
	 * 查询用户兑换券列表
	 * @param paramsMap
	 * @return rtnMap
	 * @throws Exception
	 */
	@Override
	public Map<String,Object> queryShopVochers(Map<String, Object> paramsMap) 
			throws Exception {
		Map<String,Object> rtnMap = new HashMap<String,Object>();
		
		int totalNum = shopVouchersDao.queryShopVochersCount(paramsMap);
		List<ShopVouchers> shopVoucherList = new ArrayList<ShopVouchers>();
		if (totalNum > 0) {
			shopVoucherList = shopVouchersDao.queryShopVochers(paramsMap);
		}
		rtnMap.put("list", shopVoucherList);
		rtnMap.put("rescode", Consts.SUCCESS_CODE);
		rtnMap.put("resmsg_cn", "查询成功"); 
		rtnMap.put("listSize", shopVoucherList.size());
		rtnMap.put("totalNum", totalNum);
		
		return rtnMap;
	}
	
	/**
	 * 查询用户兑换券数量
	 * @param paramsMap
	 * @return rtnMap
	 * @throws Exception
	 */
	@Override
	public int shopVochersCount(Map<String, Object> paramsMap) 
			throws Exception {
		return shopVouchersDao.queryShopVochersCount(paramsMap);
	}
	
	/**
	 * 跳转电商一元购平台
	 * @param paramsMap
	 * @return rtnMap
	 * @throws Exception
	 */
	@Override
	public Map<String,Object> goUseShopVouchers(String mobile) 
			throws Exception {
		Map<String,Object> rtnMap = new HashMap<String,Object>();
		
		Map<String,String> sysValue = systemSettingDao.getSystemSettingValue("yygurl");
		String url ="";
		String webTitle="";
		if (null !=sysValue) {
			url = sysValue.get("value") == null ? "":sysValue.get("value");
			webTitle = sysValue.get("commet") == null ? "":sysValue.get("commet");
		}
		logger.info("mobile:" + mobile + "跳转基本url:" + url + "标题：" + webTitle);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String time = sdf.format(new Date());

		String sign = getSign(mobile,time,"LBJR");
		// login接收的数据
		Map<String, Object> userMap = new HashMap<String, Object>();
		userMap.put("mobile", mobile);
		userMap.put("from", "LBJR");
		userMap.put("time", time);
		userMap.put("sign", sign);
		String param = CommonUtil.getParam(userMap);
		String loginParm = "";
		try {
			loginParm = DES3Util.encodeShop(param);
		} catch (Exception e) {
			logger.error("跳转电商参数加密失败:" + e);
			e.printStackTrace();
		}
		String yygurl = url+loginParm;
		logger.info("yygurl:" + yygurl);
		rtnMap.put("yygurl", yygurl);
		rtnMap.put("webTitle", webTitle);
		rtnMap.put("rescode", Consts.SUCCESS_CODE);
		rtnMap.put("resmsg_cn", "查询成功"); 
		
		return rtnMap;
	}
	
	/**
	 * 查询用户兑换券数量（电商）
	 * @param paramsMap
	 * @return rtnMap
	 * @throws Exception
	 */
	@Override
	public Map<String,Object> queryVouCountToShop(Map<String, Object> paramsMap) 
			throws Exception {
		Map<String,Object> rtnMap = new HashMap<String,Object>();
		
		int vouCount = shopVouchersDao.queryShopVochersCount(paramsMap);
		rtnMap.put("rescode", Consts.SUCCESS_CODE);
		rtnMap.put("resmsg_cn", "查询成功"); 
		rtnMap.put("vouCount", vouCount);
		
		return rtnMap;
	}
	
	/**
	 * 查询用户已使用兑换券数量（电商）
	 * @param paramsMap
	 * @return rtnMap
	 * @throws Exception
	 */
	@Override
	public Map<String,Object> queryVouchersToShop(Map<String, Object> paramsMap) 
			throws Exception {
		Map<String,Object> rtnMap = new HashMap<String,Object>();
		
//		int voucherNum = shopVouchersDao.queryVouchersToShop(paramsMap);;
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//		String buyTime = paramsMap.get("buyTime").toString();
//		Date date_01 = sdf.parse(buyTime);
//		Date date_02 = sdf.parse(sdf.format(new Date()));
//		if(voucherNum==0) {
		int voucherNum = shopVouchersDao.queryOldVouchersToShop(paramsMap);

		rtnMap.put("rescode", Consts.SUCCESS_CODE);
		rtnMap.put("resmsg_cn", "查询成功"); 
		rtnMap.put("voucherNum", voucherNum);
		
		return rtnMap;
	}
	
	/**
	 * 更新兑换券使用状态
	 * @param paramsMap
	 * @return rtnMap
	 * @throws Exception
	 */
	@Override
	public Map<String,Object> updateShopVochers(Map<String, Object> paramsMap) 
			throws Exception {
		Map<String,Object> rtnMap = new HashMap<String,Object>();
		String vouCount = paramsMap.get("vouCount")==null?"":paramsMap.get("vouCount").toString();
		if (!"".equals(vouCount) && !"0".equals(vouCount)) {
			int orderCount = shopVouchersDao.queryOldVouchersToShop(paramsMap);
			if (orderCount > 0) {
				rtnMap.put("rescode", Consts.BUSINESSE_CODE);
				rtnMap.put("resmsg_cn", "该订单已经存在！");
				return rtnMap;
			}
			int upcount = shopVouchersDao.updateShopVochers(paramsMap);
			if (upcount==0) {
				rtnMap.put("rescode", Consts.CHECK_CODE);
				rtnMap.put("resmsg_cn", "更新兑换券状态失败！"); 
			} else {
				rtnMap.put("rescode", Consts.SUCCESS_CODE);
				rtnMap.put("resmsg_cn", "更新兑换券状态成功！");
			}
		} else {
			rtnMap.put("rescode", Consts.SUCCESS_CODE);
			rtnMap.put("resmsg_cn", "传入兑换券数量参数为0！");
		}
		return rtnMap;
	}
	
	/**
	 * 电商验签
	 * @param mobile
	 * @param time
	 * @param from
	 * @return sign
	 */
	private String getSign(String mobile,String time,String from) {
		StringBuilder buff = new StringBuilder(1024);
		String privateKey = "";
		String sign = "";
		try {
			Properties props = PropertiesLoaderUtils.loadAllProperties("shopKey.properties");
			privateKey = props.getProperty("privateKey");
		} catch (IOException e) {
			logger.error(e);
		}
		buff.append(mobile).append("|")
				.append(time).append("|")
				.append(from);
		try {
			sign = MacUtil.genMac(privateKey, buff.toString());
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sign;
	}
}
